<?php

namespace Modules\DataCheck\Excel\Import;

use Modules\DataCheck\Excel\Tratis\Excel;
use Modules\DataCheck\Exceptions\DataCheckException;

/**
 * 待核对数据读取
 */
class TargetDataRead
{
    use Excel;

    /**
     * 跳过的行数
     * @var int
     */
    private int $skipLine = 1;

    /**
     * 字段映射
     * @var array
     */
    private array $fieldMap = [
        1 => 'department', //部门
        2 => 'org', //领用人/机构
        3 => 'code', //单证编号
        4 => 'name',  //单证名称,
        5 => 'serial_num_start', //开始流水号
        6 => 'serial_num_end', //结束流水号
        7 => 'num', //数量
    ];

    /**
     * @param string $file
     * @return array
     * @deprecated
     */
    public function  handle(string $file): array
    {
        if (!file_exists($file)) {
            throw new DataCheckException('文件不存在', ErrorEnum::EXCEL);
        }

        $pathInfo = pathinfo($file);
        $reader  = new \Vtiful\Kernel\Excel(['path' => $pathInfo['dirname']]);
        $sheetList = $reader->openFile($pathInfo['basename'])->sheetList();
        if (empty($sheetList)) {
            return [];
        }

        $data = [];
        foreach ($sheetList as $sheetName) {
            $reader->openSheet($sheetName)->setSkipRows($this->skipLine);

            $line = $this->skipLine + 1;
            $data[$sheetName] = [];
            while (($row = $reader->nextRow()) !== null  && array_filter($row) !== []) {
                $rowData = $this->transDataT($this->fieldMap, $row, [], false, $line);
                $rowData['line'] = $line++;
                $data[$sheetName][] = $rowData;
            }
        }
        $reader->close();

        return $data;
    }

    /**
     * 获取文件行数
     * @param string $file
     * @param int    $skipLine
     * @return int
     */
    public function getFileLineCount(string $file, int $skipLine = 1): int
    {
        if (!file_exists($file)) {
            throw new DataCheckException('文件不存在', ErrorEnum::EXCEL);
        }

        $pathInfo = pathinfo($file);
        $reader  = new \Vtiful\Kernel\Excel(['path' => $pathInfo['dirname']]);
        $sheetList = $reader->openFile($pathInfo['basename'])->sheetList();
        if (empty($sheetList)) {
            return 0;
        }

        $total = 0;
        foreach ($sheetList as $sheetName) {
            $reader->openSheet($sheetName)->setSkipRows($skipLine);
            while (($row = $reader->nextRow()) !== null  && array_filter($row) !== []) {
                $total++;
            }
        }
        $reader->close();

        return $total;
    }
}